package com.ybwh.springboot1.websocket.client;

import javax.websocket.ClientEndpoint;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@ClientEndpoint
public class MyClient {
    private static Logger logger = LoggerFactory.getLogger(MyClient.class);
    private Session session;
    @OnOpen
    public void open(Session session){
        logger.info("Client WebSocket is opening...");
        this.session = session;
        System.out.println("sessionId"+session.getId());
    }

    @OnMessage
    public void onMessage(String message){
        logger.info("Server send message: " + message);
        System.out.println("onMessage:"+Thread.currentThread().getId());
    }

    @OnClose
    public void onClose(){
        logger.info("Websocket closed");
    }

    /**
     * 发送客户端消息到服务端
     * @param message 消息内容
     */
    public void send(String message){
        this.session.getAsyncRemote().sendText(message);
        System.out.println("onMessage:"+Thread.currentThread().getId());
    }
}